<template>
  <div class="user-container">
    <!-- 面包屑 -->
    <!--  <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: 'welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>-->
    <bread :second="'用户管理'" :third="'用户列表'"></bread>
    <!-- 卡片框 -->
    <el-card class="box-card">
      <!--------------------- input 搜索 -------------------------------->
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-input
              placeholder="请输入内容"
              v-model="queryInfo.query"
              class="input-with-select"
              clearable
              @clear="getuserList()"
            >
              <el-button slot="append" icon="el-icon-search" @click="getuserList()"></el-button>
            </el-input>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <!--############### 添加按钮 ###############-->
            <el-button type="primary" @click="addUsers()">添加用户</el-button>
          </div>
        </el-col>
      </el-row>
      <!---------------------- 表格 --------------------------->
      <el-table :data="tableData" border stripe style="width: 100%">
        <el-table-column type="index" width="50" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名" width="180"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <!--############# 用插槽 包装按钮，点击可以获取scope.row 数据 #####################-->
          <!----------- 改变用户状态按钮 --------------->
          <template slot-scope="scope">
            <!-- ==={{scope.row.id}}==={{scope.row.mg_state}}=== -->
            <el-switch
              v-model="scope.row.mg_state"
              @change="changeUserstate(scope.row)"
              active-color="#13ce66"
              inactive-color="#ff4949"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!---------------------- 修改按钮 ------------------------------->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="editUsers(scope.row)"></el-button>
            <!------------------------ 删除按钮 --------------------------->
            <el-button
              type="danger"
              @click="delUsers(scope.row.id)"
              icon="el-icon-delete"
              size="mini"
            ></el-button>
            <!--------------------------- 分配角色按钮 --------------------------------->
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button
                type="warning"
                icon="el-icon-share"
                size="mini"
                @click="allotRoles(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!--------------------- 分页 ---------------------------->
      <div class="block" style="margin-top:20px">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pagenum"
          :page-sizes="[5, 10, 50,100]"
          :page-size="queryInfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
    </el-card>
    <!------------------------ 修改按钮弹出框 --------------------------------->
    <el-dialog title="修改用户" :visible.sync="dialogFormVisible">
      <el-form :model="form" ref="form" :rules="rulesForm">
        <el-form-item prop="username" label="用户名" :label-width="formLabelWidth">
          <el-input v-model="form.username" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form-item prop="email" label="邮箱" :label-width="formLabelWidth">
          <el-input v-model="form.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="mobile" label="手机号" :label-width="formLabelWidth">
          <el-input v-model="form.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('form')">确 定</el-button>
      </div>
    </el-dialog>
    <!----------------------------- 添加按钮弹出框 ------------------------------------>
    <el-dialog title="添加用户" :visible.sync="dialogFormVisibleAdd">
      <el-form ref="dialogAddForm" :model="addForm" :rules="rulesFormAdd">
        <el-form-item prop="username" label="用户名" :label-width="formLabelWidth">
          <el-input v-model="addForm.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="password" label="密码" :label-width="formLabelWidth">
          <el-input v-model="addForm.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="email" label="邮箱" :label-width="formLabelWidth">
          <el-input v-model="addForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="mobile" label="手机" :label-width="formLabelWidth">
          <el-input v-model="addForm.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancleAdd()">取 消</el-button>
        <el-button type="primary" @click="addFormUser()">确 定</el-button>
      </div>
    </el-dialog>
    <!------------------------------- 分配角色按钮弹窗 --------------------------------------->
    <el-dialog title="分配角色" :visible.sync="allotRolesDialog">
      <el-form ref="rolesForm" :model="rolesForm">
        <el-form-item label="当前的用户" label-width="100px">{{objRoles.username}}</el-form-item>
        <el-form-item label="当前的角色" label-width="100px">{{objRoles.role_name}}</el-form-item>
        <el-form-item label="分配新角色" label-width="100px">
          <el-select v-model="rolesForm.rid" placeholder="请选择">
            <el-option
              v-for="(item,index) in  roleList"
              :key="index"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="allotRolesDialog=false">取 消</el-button>
        <el-button type="primary" @click="rolesFormSet()">确 定</el-button>
      </div>
    </el-dialog>
    <!-----------------------------------end--------------------------------------- -->
  </div>
</template>

           
<script>
import {
  users_api,
  userState_api,
  delUsers_api,
  editUsers_api,
  addUsers_api,
  rolesList_api,
  allotRoles_api,
  userSearch_api
} from "@/api/login_api.js";
export default {
  data() {
    //设置邮箱校验的正则表达式-------------------------------------
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
      if (regEmail.exec(value)) {
        //合法的邮箱
        return callback();
      }
      callback(new Error("请输入正确的邮箱"));
    };
    return {
      input: "",
      tableData: [],
      total: 0,
      //分页------------
      queryInfo: {
        query: "", //查询参数
        pagenum: 1,
        pagesize: 5
      },
      //是否打开修改按钮的弹出框
      dialogFormVisible: false,
      dialogFormVisibleAdd: false,
      allotRolesDialog: false,
      form: {},
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      objRoles: {},
      roleList: [],
      rolesForm: {
        rid: "",
        id: JSON.parse(window.sessionStorage.getItem("user"))
      },
      formLabelWidth: "120px",

      //添加校验规则---------------------------------------
      rulesForm: {
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" }
          // { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "change" },
          { min: 11, max: 11, message: "请输入11位手机号", trigger: "blur" }
        ]
      },
      rulesFormAdd: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" }
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [{ required: true, message: "请输入手机号", trigger: "blur" }]
      }
    };
  },
  //获取后端数据,渲染页面------------------------------------------
  created() {
    this.getuserList();
  },
  methods: {
    //element-ui组件 【分页】------------------------------
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.queryInfo.pagesize = val;
      this.getuserList();
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.queryInfo.pagenum = val;
      this.getuserList();
    },
    //1、axios发送请求------------------------------------------
    async getuserList() {
      const { data: res } = await users_api(this.queryInfo);
      // console.log(res,555555);
      if (res.meta.status !== 200) return this.$message("获取数据失败");
      this.tableData = res.data.users;
      this.total = res.data.total;
    },
    //2、修改用户状态  要用change事件
    async changeUserstate(scopeRow) {
      // console.log(scopeRow,77777);
      const { data: res } = await userState_api({
        uId: scopeRow.id,
        type: scopeRow.mg_state
      });
      // console.log(res,6666666);
    },
    //3、删除用户数据----------------------------------------------------------
    async delUsers(id) {
      //  console.log(id,1111111);
      const res = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(() => {
        this.$message({
          type: "info",
          message: "已取消删除"
        });
      });
      // console.log(res,222222);
      if (res == "confirm") {
        const { data: res2 } = await delUsers_api(id);
        // console.log(res2,33333);
        //重新渲染页面
        this.getuserList();
        this.$message({
          type: "success",
          message: "删除成功!"
        });
      }
    },
    //4、修改用户信息-------------------------------------------------------------
    editUsers(row) {
      this.dialogFormVisible = true;
      //  console.log(row);
      this.form = row;
    },
    submitForm(form) {
      // console.log(formName,444444);
      this.$refs[form].validate(async valid => {
        if (valid) {
          //发送ajax请求
          const { data: res } = await editUsers_api(this.form);
          this.dialogFormVisible = false;
          //涮新页面
          this.getuserList();
        } else {
          return;
        }
      });
    },
    //5、添加用户信息----------------------------------------------------
    addUsers() {
      //点击按钮，显示弹窗
      this.dialogFormVisibleAdd = true;
    },
    addFormUser() {
      this.$refs.dialogAddForm.validate(async valid => {
        if (valid) {
          //发送ajax请求
          const { data: res } = await addUsers_api(this.addForm);
          // console.log(this.addForm,333333333);
          // console.log(res,5555555);
          this.dialogFormVisibleAdd = false;
          //涮新页面
          this.getuserList();
          // 清空表单数据
          this.$refs.dialogAddForm.resetFields();
        } else {
          return;
        }
      });
    },
    //6、点击取消按钮--------------------------------------------------
    cancleAdd() {
      this.dialogFormVisibleAdd = false;
      // 清空表单数据
      this.addForm = {};
    },
    //7、点击分配角色按钮------------------------------------------
    async allotRoles(row) {
      this.allotRolesDialog = true;
      this.objRoles = row;
      const { data: res } = await rolesList_api();
      // console.log(res,333333);
      this.roleList = res.data;
    },
    //8、点击弹窗确认，分配用户角色-------------------------------------
    async rolesFormSet() {
      const { data: res } = await allotRoles_api(this.rolesForm);
      console.log(res, 66666);
      this.allotRolesDialog = false;
      this.getuserList();
    }
    //9、根据 ID 查询用户信息---------------------------------------
  }
};
</script>
<style scoped lang="less">
.user-container {
  .el-card {
    margin-top: 20px;
    .el-table {
      margin-top: 20px;
    }
  }
}
</style>